<template>
  <div class="song">
    <div class="top" v-if="searchInfo.artist">
      <h3 class="result">找到 {{ songCount }} 首单曲</h3>
      <div class="good">
        <p class="title">最佳匹配</p>
        <div class="singer" @click="goSinger(searchInfo.artist[0].id)">
          <img
            :src="searchInfo.artist[0].img1v1Url + '?param==200y200'"
            alt=""
          />
          <div class="sinerRight">
            <span class="singerInfo"
              >歌手: {{ searchInfo.artist[0].name }}</span
            >
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="table">
      <el-table
        :data="searchSongList"
        stripe
        lazy
        style="width: 100%"
        v-infinite-scroll="this.$store.state.isLogin ? loadMore : ''"
        :infinite-scroll-disabled="scrollLoadDisabled"
        :infinite-scroll-distance="300"
        :infinite-scroll-immediate="false"
        @row-dblclick="doubleClick"
        @cell-click="handelCellClick"
      >
        <el-table-column
          min-width="80"
          label="序号"
          type="index"
          :index="handleIndex"
        >
        </el-table-column>
        <el-table-column min-width="30" label="下载">
          <i class="el-icon-download"></i
        ></el-table-column>
        <el-table-column
          prop="name"
          label="标题"
          min-width="350"
        ></el-table-column>
        <el-table-column
          prop="ar[0].name"
          label="歌手"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="al.name"
          label="专辑"
          min-width="170"
        ></el-table-column>
        <el-table-column
          prop="dt"
          label="时长"
          min-width="100"
        ></el-table-column>
      </el-table>
    </div>
    <el-backtop target=".song"></el-backtop>
  </div>
</template>
<script>
import { getMusicUrl } from '@/api/music/music'
import { getSearchBestMatch } from '@/api/search/search'
import { handleMusicTime } from '@/plugins/utils'
export default {
  data() {
    return {
      // 搜索的信息
      searchInfo: {},
      // 是否禁止滚动加载
      scrollLoadDisabled: false,
      // 搜索歌曲列表
      searchSongList: [],
      // 搜索总条数
      songCount: 0,
      // 页数
      currentPage: 1
    }
  },
  methods: {
    // 获取最佳匹配
    async getSearchBestMatch() {
      let res = await getSearchBestMatch({
        keywords: this.$route.query.name
      })
      this.searchInfo = res.data.result
      console.log(this.searchInfo)
    },
    // 请求搜索单曲
    async getSearchSong() {
      this.scrollLoadDisabled = true
      let res = await this.$request('/cloudsearch', {
        keywords: this.$route.query.name,
        offset: 30 * (this.currentPage - 1)
      })
      // console.log(res)
      this.songCount = res.data.result.songCount
      this.searchSongList.push(...res.data.result.songs)
      // 对数据的音乐时长进行处理
      this.searchSongList.forEach((item, index) => {
        this.searchSongList[index].dt = handleMusicTime(item.dt)
      })
      this.scrollLoadDisabled = false
    },
    // 去歌手主页
    goSinger(id) {
      this.$router.push({ path: '/index/singerDetail', query: { id } })
    },
    // 点击加载所有音乐的回调
    loadMore() {
      this.scrollLoadDisabled = true
      if (!this.$store.state.isLogin) {
        this.$message.error('请先进行登录操作!')
        return
      }
      this.currentPage++
      this.getSearchSong()
    },
    // 双击播放
    doubleClick(row) {
      console.log(row, '双击播放')
      // 获取当前歌单列表
      let musicList = this.$store.state.musicList
      // 获取当前播放歌曲索引
      let currentIndex = this.$store.state.currentIndex
      // 看当前歌单中是否有点击的歌曲
      let isHave = musicList.find((item) => item.id === row.id)
      if (isHave) {
        // 如果存在只需要直接改变播放的歌曲id
        this.$store.commit('updateMusicId', row.id)
      }
      // 如果不存在，将这首歌曲插入已有列表中
      musicList.splice(currentIndex + 1, 0, row)
      this.$store.commit('updateMusicId', row.id)
      this.$store.commit('updateMusicList', {
        musicList,
        musicListId: this.$store.state.musicListId
      })
    },
    // 点击下载
    async handelCellClick(cell, row, column) {
      if (column?.children[0]?.children[0]?.className === 'el-icon-download') {
        // console.log('找到了')
        // this.$message.warning('敬请期待!')
        // console.log(row, cell)
        let res = await getMusicUrl(cell.id)
        // console.log(res, row, cell)
        const musicUrl = res.data.data[0].url
        // console.log(res.data.data[0].url)
        // 匹配资源的域名
        let url = res.data.data[0].url.match(/http.*?\.net/)
        // console.log(url)
        // 匹配域名名称，并匹配对应的代理
        let serve = url[0].match(/http:\/(\S*).music/)[1]
        // console.log(serve)
        // 截取后面的参数
        let params = res.data.data[0].url.slice(url[0].length)
        if (
          serve != '/m7' &&
          serve != '/m701' &&
          serve != '/m8' &&
          serve != '/m801'
        ) {
          // 没有对应的代理
          this.$message.error('匹配不到对应的代理,下载失败!')
          return
        }
        // console.log(params)
        if (musicUrl === null) {
          this.$message.warning('暂时无法获取资源')
        }
        let downloadMusicInfo = {
          url: serve + params,
          name:
            cell.name +
            ' - ' +
            cell.ar[0].name +
            '.' +
            res.data.data[0].type.toLowerCase()
        }
        // console.log(downloadMusicInfo)
        this.$store.commit('updateDownloadMusicInfo', downloadMusicInfo)
        // try {
        //   let link = document.createElement('a')
        //   link.style.display = 'none'
        //   link.href = window.URL.createObjectURL(new Blob([serve + params]))
        //   link.setAttribute(
        //     'download',
        //     cell.name +
        //       '-' +
        //       cell.ar[0].name +
        //       '.' +
        //       res.data.data[0].type.toLowerCase()
        //   )
        //   // link.download =
        //   //   cell.name +
        //   //   '-' +
        //   //   cell.ar[0].name +
        //   //   '.' +
        //   //   res.data.data[0].type.toLowerCase()
        //   document.body.appendChild(link)
        //   link.click()
        // } catch (error) {
        //   console.log(error)
        // }
      }
    },
    handleIndex(index) {
      index += 1
      if (index < 10) {
        return (index = '0' + index)
      } else {
        return index
      }
    }
  },
  created() {
    this.getSearchBestMatch()
  }
}
</script>
<style lang="scss" scoped>
.top {
  .result {
    font-size: 20px;
    margin-bottom: 5px;
  }
  .good {
    .title {
      font-size: 16px;
      color: #222;
      margin-bottom: 5px;
    }
    .singer {
      width: 350px;
      height: 80px;
      display: flex;
      background-color: #f4f4f4;
      border-radius: 10px;
      overflow: hidden;
      align-items: center;
      cursor: pointer;
      img {
        width: 35%;
        height: 100%;
        background-color: pink;
      }
      .sinerRight {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-left: 10px;
        // transform: translateY(-10%);
        color: #222;
        .el-icon-arrow-right {
          margin-right: 10px;
          font-size: 22px;
        }
      }
    }
  }
}
.song {
  height: 74vh;
  overflow-x: hidden;
}
</style>
